package com.hontech.desktoppastacooker.device

import android.util.Log
import com.hontech.desktoppastacooker.codec.decodeUint16
import com.hontech.desktoppastacooker.conn.frame.NotifyFrame
import com.hontech.desktoppastacooker.conn.serial.ByteView
import com.hontech.desktoppastacooker.conn.serial.Uint8
import com.hontech.desktoppastacooker.utils.eventBus
import com.hontech.desktoppastacooker.utils.log
import com.hontech.desktoppastacooker.utils.toEpcHex
import com.hontech.desktoppastacooker.utils.toHex

object Device {

    const val RFID_CMD_EPC = 0x22

    val status = Status()

    fun recvStatus(frame: NotifyFrame) {
        frame.parse(arrayOf(
            status.appVersion,
            status.sw,
            status.sensor,
            status.kpa,
            status.steamTemp,
            status.flowCount,
            status.adc,
            status.parts,
            status.draw,
            status.heat
        ))
        eventBus.post(StatusEvent())
    }

    fun recvRfid(frame: NotifyFrame) {
        val cmd = Uint8()
        val param = ByteView()
        frame.parse(arrayOf(cmd, param))
        when (cmd.value) {
            RFID_CMD_EPC -> handleEPC(param)
        }
    }

    private fun handleEPC(param: ByteView) {
        if (param.len != 0x11) {
            Log.e("epc", "handleEPC: epc fail ${param.len}")
            return
        }

        val rssi = param.data[param.index].toInt() // 1byte
        val pc = decodeUint16(param.data, param.index + 1) // 2byte
        val epc = param.data.toEpcHex(param.index + 3, param.len - 5)
        val crc = decodeUint16(param.data, param.index + param.len - 2) // 2byte
        val rfid = Rfid(rssi, pc, epc, crc)
       // log("rfid:$rfid")
        eventBus.post(RfidEvent(rfid))
    }
}

